import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Input, Modal, InputNumber, Upload, Button, Icon, Select, Radio } from 'antd';
import { formatMessage } from 'umi-plugin-react/locale';
import { FormComponentProps } from '@ant-design/compatible/es/form';
import React, { useState } from 'react';

// 导入自定义组件1
import PreviewForm from '@/components/PreviewForm';
import * as BdHelper from '@/utils/BdHelper';
import * as DataHelper from '@/helpers/DataHelper';
import * as TsxHelper from '@/helpers/TsxHelper';

// 常量
const { TextArea } = Input;
const FormItem = Form.Item;

// 定义: 数据表单属性
interface DataFormProps extends FormComponentProps {
  dataModalVisible: boolean;
  isUpdate: boolean
  dataFormValues: any
  common: any
  onSubmit: (fieldsValue: any) => any;
  onCancel: () => void;
}

// 数据表单
const DataForm: React.FC<DataFormProps> = props => {
  // 组件属性
  const { dataModalVisible, form, onSubmit: handleSubmit, onCancel,
    common, isUpdate,dataFormValues } = props;

  // 图片状态
  const [picture, setPicture] = useState<any[]>([]);
  const [uploadChanged, setUploadChanged] = useState<boolean>(false);
  const [previewModelVisible, handlePreviewModalVisible] = useState<boolean>(false);
  const [previewImg, setPreviewImg] = useState('');

  //提交表单
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      if(picture.length > 0){
        fieldsValue.file_id   = picture[0].file_id
        fieldsValue.file_url  = picture[0].file_url
      }
      // 如果是更新
      if(isUpdate){
        fieldsValue.id = dataFormValues.id;
      }
      console.log("submit fields ", fieldsValue)

      // 如果更新成功之后，重置表单
      handleSubmit(fieldsValue).then((success:any) => {
        console.log('handleSubmit then success is ', success)
        if(success){
          form.resetFields()
          setPicture([])
        }
      })

    });
  };

  // 设置上传文件值
  const setUploadFile = (fileList:any) => {
    setUploadChanged(true)
    let fileArr = DataHelper.getLastUploadFile(fileList)
    console.log("fileArr is ", fileArr)
    if(fileArr.length > 0){
      setPicture(fileArr)
      setPreviewImg(fileArr[0].file_url)
    }else if(fileArr.length === 0){
      console.log('set picture []')
      setPicture([])
    }
  }

  // 初始化变量
  const token = BdHelper.getBdToken()

  // 编辑时初始化 picture
  const defaultPicture = DataHelper.buildFileByUrl(dataFormValues.file_url)

  // 是否展示图片上传按钮
  const showUploadButton = DataHelper.showUploadBtn(isUpdate, picture, defaultPicture, uploadChanged)

  // 弹出框
  // @ts-ignore
  return <Modal
    destroyOnClose
    title={formatMessage({ id: 'app.base.create' })}
    width={DataHelper.DEFAULT_MODAL_WIDTH}
    visible={dataModalVisible}
    onOk={okHandle}
    onCancel={() => onCancel()}
  >
    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={formatMessage({ id: 'app.base.name' })}>
      {form.getFieldDecorator('name', {
        initialValue: isUpdate ? dataFormValues.name : '',
        rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
      })(<Input placeholder={formatMessage({ id: 'app.base.please_input' })}/>)}
    </FormItem>

    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={formatMessage({ id: 'app.base.picture' })}>
      {form.getFieldDecorator('picture', {
        // initialValue: defaultPicture,
        // rules: [{required: true, message: '请上传图片'}],
      })(
        <Upload
          listType={'picture'}
          className={'upload-list-inline'}
          action="/api/admin/file/upload"
          defaultFileList={defaultPicture}
          beforeUpload={(file) => {
            console.log('before upload file type:', file.type)
            // todo: 这里可以对上传文件类型做限制
            return true;
          }}
          data={{ type: 'image' }}
          onRemove={() => setPicture([])}
          onChange={(changeObj) => setUploadFile(changeObj.fileList)}
          onPreview={() => handlePreviewModalVisible(true)}
          headers={{
            Authorization: `Bearer ${token}`,
          }}
        >
          {
            showUploadButton ? (
              <Button>
                <Icon type="upload"/> {formatMessage({ id: 'app.base.upload' })}
              </Button>
            ) : null
          }
        </Upload>
      )}
    </FormItem>

    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={formatMessage({ id: 'app.base.type' })}>
      {form.getFieldDecorator('type', {
        initialValue: isUpdate ? (dataFormValues.type).toString() : undefined,
        //  rules: [{ required: true, message: '请选择！',}],
      })(<Select placeholder={formatMessage({ id: 'app.base.please_select' })} size={'default'} style={{ width: '100%' }}>
        {common.selectOption && TsxHelper.buildSelectOption(common.selectOption)}
      </Select>)}
    </FormItem>

    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={formatMessage({ id: 'app.base.type_radio' })}>
      {form.getFieldDecorator('type', {
        initialValue: isUpdate ? dataFormValues.type : 1,
        // rules: [{ required: true, message: '请选择！',}],
      })(<Radio.Group buttonStyle="solid">
          {common.selectOption && TsxHelper.buildRadioOption(common.selectOption)}
        </Radio.Group>
      )}
    </FormItem>

    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={formatMessage({ id: 'app.base.remark' })}>
      {form.getFieldDecorator('remark', {
        initialValue: isUpdate ? dataFormValues.remark : '',
        rules: [],
      })(<TextArea rows={2} placeholder={formatMessage({ id: 'app.base.please_input' })} />)}
    </FormItem>
    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={formatMessage({ id: 'app.base.rank_num' })}>
      {form.getFieldDecorator('rank_num', {
        initialValue: isUpdate ? dataFormValues.rank_num : 888,
        rules: [],
      })(<InputNumber placeholder={formatMessage({ id: 'app.base.please_input' })} style={{ width: '100%' }} min={1}/>)}
    </FormItem>
    {
      previewModelVisible && (
        <PreviewForm
          previewModelVisible={previewModelVisible}
          onVisibleModel={handlePreviewModalVisible}
          previewImg={previewImg}
        />
      )
    }
  </Modal>;
};

export default Form.create<DataFormProps>()(DataForm);
